import { transformParams } from '@/utils/utils';
import { WaterMark } from '@ant-design/pro-components';
import type { ProTableProps } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { FC } from 'react';
import { useMemo } from 'react';

export interface Params {
  page: number; //pageIndex
  per_page: number; //pageSize
  [key: string]: any;
}

interface TableProps {
  getDataSource?: (k: any) => Promise<any>;
  fields: Array<FieldProps>;
  rowSelection?: any;
  rowKey?: string | ((record: any) => string);
}

export interface TableListProps
  extends ProTableProps<Record<string, any>, Record<string, any>, 'text'> {
  getDataSource?: (
    params: Params,
  ) => Promise<{ data?: []; total?: number; success?: boolean } | any>;
  fields: FieldProps[];
}

const TableList: FC<TableProps> = (props) => {
  const { getDataSource } = props;
  const columns: any[] = useMemo(() => {
    let _columns = props.fields.filter((item: FieldProps) => item['list'] || item['search']);
    _columns = _columns.map((v: any) => {
      const field = {
        ...v,
        hideInTable: !v.list,
        hideInSearch: !v.search,
      };
      return field;
    });
    return _columns;
  }, [props.fields]);
  // 为了支持排序,防止重复刷新, 当fields为空时不渲染table
  if (columns.filter((item) => item.valueType !== 'hidden').length === 0) {
    return <></>;
  }
  return (
    <>
      <WaterMark content={'轻岳'}>
        <ProTable
          columns={columns}
          rowSelection={props.rowSelection || {}}
          search={{ defaultCollapsed: false }}
          pagination={{ defaultPageSize: 20 }}
          size="large"
          scroll={{ x: 'max-content' }}
          request={
            getDataSource
              ? (params, sort) => getDataSource(transformParams(params, sort))
              : undefined
          }
          rowKey={props.rowKey || 'id'}
          {...props}
        />
      </WaterMark>
    </>
  );
};

export default TableList as (props: TableListProps) => JSX.Element;
